
import { createApp, h,provide,render,VNode, getCurrentInstance,App } from 'vue'
import { DialogProps } from './dialog'
import Dialog from './index.vue'

// import Icon from '@/components/icon'
// import Button from '@/components/button'

/**
 * 
 * 使用 createApp
 * 
 * @param options 
 */
const OpenDialog2=(options: DialogProps):void =>{
    const dom:HTMLElement = document.createElement('div')
    // 1. 创建弹框组件实例
    const modalApp = createApp(Dialog, {
        // 控制弹框是否显示
        visible: true,
        // 传入弹框标题
        title: options.title,
        // 传入弹框内容
        content: options.content ,
        // 传入关闭弹框的方法
        onCancel: () => {
            options.onCancel?.()
            modalApp.unmount()
            document.body.removeChild(dom)
        },
        onConfirm: () => {
            options?.onConfirm?.()
            modalApp.unmount()
            document.body.removeChild(dom)
        },
    })
    // 2. 创建渲染节点
    document.body.appendChild(dom)
    // 3. 将实例挂载到页面节点上
    modalApp.mount(dom) 
    // .use(Icon).use(Button)
}

const OpenDialog = (props) => { 
    console.log('OpenDialog',props)
    const el: HTMLElement = document.createElement('div')
  
   
   
    // if (el && vNode.el) { 
    //     document.body.appendChild(el.childNodes[0])
    // }
    // return vNode
}
const destroy = (el: HTMLElement | null | undefined, vNode: VNode | null) => {
    if (el) {
        render(null, el)
        el.remove()
    }

    el = null
    vNode = null
}



const mount = (
    component: any,
    { props,appContext}
): { vNode: VNode; el?: HTMLElement } => {
    const el: HTMLElement | undefined = document?.createElement('div')

    // eslint-disable-next-line prefer-const
    let vNode: VNode | null
    
    const onCancel = (event: HTMLElement) => {
        props.onCancel?.()
        destroy(el, vNode)
    }
    const onConfirm = (event: HTMLElement) => {
        props.onConfirm?.()
        destroy(el, vNode)
    }
    vNode=h(component, {
        ...props,
        onCancel,
        onConfirm,
        visible:true
    })
    
    
    if (appContext) {
        vNode.appContext = appContext
    }
    if (el) {
        render(vNode, el)
    }
    

    return { vNode, el }
}


export const createDialog = ( app:App,props: DialogProps): VNode => {
    const { vNode, el } = mount(Dialog, {props,appContext:app?._context} )

    if (el && vNode.el) {
        document.body.appendChild(el.childNodes[0])
    }
    return vNode
}
 

export default createDialog